package com.lifeng.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:lifeng
 * @date:2020/4/17 16:43
 */
public class JwtTest {
    private static String secret = "2345664jfdfhsas";

    public static void main(String[] args) {
        String token = createToken();
        System.out.println(token);
        String tmp = "eyJ1c2VyTmFtZSI6IuW8oOS4iSIsImV4cCI6MjU4NzExNzE5NSwidXNlcklkIjoiMTIzNDU2IiwiaWF0IjoxNTg3MTE3MTM1fQ==.tchV_ow7ldKRFgn6zl7vSqtE8P9-3LbQnvKOxdYPD0BEFcLn9vtODfIVJlUPBvw-tY_tECMYFf6RwZr1ObrF-g";
        Jws<Claims> data = parseToken(tmp);
        System.out.println(data.getBody().getExpiration());
    }

    public static String createToken(){
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId","123456");
        claims.put("userName","张三");
        Date now = new Date();
        String token = Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)   //发布时间
                .setExpiration(DateUtils.addMinutes(now,1)) //过期时间
                .signWith(SignatureAlgorithm.HS512, secret).compact();

        /*
        这两个必须在setClaims之后 不然无效
        .setIssuedAt(now)   //发布时间
                .setExpiration(DateUtils.addMinutes(now,1)) //过期时间
         设置了过期时间 解析时过期了就报错ExpiredJwtException
                */
        return token;
    }

    public static Jws<Claims> parseToken(String token){
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token);
    }
}
